package com.bnlr.lrparking.appui.mine.mycar;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Display;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.listener.CustomListener;
import com.blankj.utilcode.util.ToastUtils;
import com.bnlr.lrparking.constant.LrConstant;
import com.bnlr.lrparking.constant.Urls;
import com.bumptech.glide.Glide;
import com.bnlr.lrparking.app.Application;
import com.bnlr.lrparking.R;
import com.bnlr.lrparking.base.BaseActivity;
import com.bnlr.lrparking.app.AppConfig;
import com.bnlr.lrparking.util.BitmapHelper;
import com.bnlr.lrparking.util.FileUtil;
import com.bnlr.lrparking.event.CloseMyCarDetailEvent;
import com.bnlr.lrparking.model.CarM;
import com.bnlr.lrparking.model.CarTypeBean;
import com.bnlr.lrparking.model.UpImgM;
import com.bnlr.lrparking.model.UploadGoodsBean;
import com.bnlr.lrparking.util.CommonUtil;
import com.bnlr.lrparking.util.Config;
import com.bnlr.lrparking.util.DbTOPxUtils;
import com.bnlr.lrparking.util.InputUtils;
import com.bnlr.lrparking.util.MyGridView;
import com.bnlr.nohttp.CallServer;
import com.bnlr.nohttp.CustomHttpListener;
import com.yolanda.nohttp.NoHttp;
import com.zzti.fengyongge.imagepicker.PhotoPreviewActivity;
import com.zzti.fengyongge.imagepicker.PhotoSelectorActivity;
import com.zzti.fengyongge.imagepicker.model.PhotoModel;
import com.zzti.fengyongge.imagepicker.util.CommonUtils;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created by hp on 2017/8/29.
 * 添加车辆
 */
public class AddCarActivity extends BaseActivity {

    private ArrayList<EditText> editTexts = new ArrayList<>(8);
    private OptionsPickerView pvCustomOptions;
    private ArrayList<String> carType = new ArrayList<>();

    private List<PhotoModel> single_photos = new ArrayList<PhotoModel>();
    private ArrayList<UploadGoodsBean> img_uri = new ArrayList<UploadGoodsBean>();
    private int screen_widthOffset;
    GridImgAdapter gridImgsAdapter;
    private String path="";
    private List<String> urlArray= new ArrayList<>();
    private Unbinder unbinder;
    @BindView(R.id.tv_nav_title)
    TextView tvNavTitle;
    @BindView(R.id.tv_addcar_btn)
    TextView tv_addcar_btn;
    @BindView(R.id.tv_car_type)
    EditText tv_car_type;
    @BindView(R.id.my_goods_GV)
    MyGridView my_imgs_GV;
    private CarM.DataBean carAgainRZ;
    private List<CarTypeBean.DataBean> typeList = new ArrayList<>();
    private int keyType;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_addcar);
        unbinder = ButterKnife.bind(this);
        initView();
        setEdtListener();
    }

    private void initView() {
//        stallType();
        getCarType();
        editTexts.add((EditText) findViewById(R.id.input_1_edt));
        editTexts.add((EditText) findViewById(R.id.input_2_edt));
        editTexts.add((EditText) findViewById(R.id.input_3_edt));
        editTexts.add((EditText) findViewById(R.id.input_4_edt));
        editTexts.add((EditText) findViewById(R.id.input_5_edt));
        editTexts.add((EditText) findViewById(R.id.input_6_edt));
        editTexts.add((EditText) findViewById(R.id.input_7_edt));
        editTexts.add((EditText) findViewById(R.id.input_8_edt));

        Intent intent = getIntent();
        carAgainRZ = (CarM.DataBean) intent.getSerializableExtra("againAudit");
        if (carAgainRZ != null) {
            tvNavTitle.setText("编辑车辆");
            tv_car_type.setText(carAgainRZ.getCarType());
            String num = carAgainRZ.getCarNum().replace(" ","");
            String[] arr = num.split("");
            for (int i = 0; i < arr.length-1; i++) {
                editTexts.get(i).setText(arr[i+1]);
            }
            for (int i = 0; i < carAgainRZ.getPhotoList().size(); i++) {
                urlArray.add(carAgainRZ.getPhotoList().get(i).getPhotoUrl());
                img_uri.add(new UploadGoodsBean(carAgainRZ.getPhotoList().get(i).getPhotoUrl(),true));
                single_photos.add(new PhotoModel(carAgainRZ.getPhotoList().get(i).getPhotoUrl(),true));
            }
        } else {
            tvNavTitle.setText("添加车辆");
        }
        tv_addcar_btn.setOnClickListener(this);
        tv_car_type.setOnClickListener(this);
        Config.ScreenMap = Config.getScreenSize(this, this);
        WindowManager windowManager = getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        screen_widthOffset = (display.getWidth() - (3* DbTOPxUtils.dip2px(this, 2)))/3;
        gridImgsAdapter = new GridImgAdapter();
        my_imgs_GV.setAdapter(gridImgsAdapter);
        if (img_uri.size() < 3) {
            img_uri.add(null);
        }
        gridImgsAdapter.notifyDataSetChanged();
        initCustomOptionPicker();

    }

    /**
     * 获取车位类型
     */
    private void getCarType() {
        try {
            mRequest = NoHttp.createStringRequest(Urls.CAR_IP, LrConstant.POST);
            mRequest.add("action", "GetCarType");
            mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));
            mRequest.add("phonePara", Application.DEVICE_ID);
            // 添加到请求队列+
            CallServer.getRequestInstance().add(baseContext, mRequest,
                    new CustomHttpListener<CarTypeBean>(baseContext, true, CarTypeBean.class) {
                        @Override
                        public void doWork(CarTypeBean data, String code) {
                            if (TextUtils.equals("1", code)) {
                                typeList = data.getData();
                                for (int i = 0; i < data.getData().size(); i++) {
                                    carType.add(data.getData().get(i).getValue());
                                }
                                if (carAgainRZ != null) {
                                    for (int i = 0; i < typeList.size(); i++) {
                                        if (carAgainRZ.getCarType().equals(typeList.get(i).getValue())) {
                                            keyType = typeList.get(i).getKey();
                                            break;
                                        }
                                    }
                                }
                            } else {
                                CommonUtil.showToask(baseContext, data.getMsg()+"");
                            }
                        }
                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {

                        }
                    }, true);
        } catch (Exception e) {
        }
    }

    private void setEdtListener() {
        for (int i = 0; i < editTexts.size(); i++) {
            editTexts.get(i).setSelection(editTexts.get(i).getText().toString().length());
            if (i == 0) {
                //设置第一个只能输入汉字的过滤器
                editTexts.get(i).setFilters(new InputFilter[]{InputUtils.getInputChineseFilter()});
            }
            editTexts.get(i).setTag(false);
            final int position = i;
            editTexts.get(i).addTextChangedListener(new TextWatcher() {

                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {

                }
                @Override
                public void afterTextChanged(Editable s) {
//                    Log.e("123456",s.toString());
                    //CommonUtil.showToask(AddCarActivity.this, s.toString());
                    //输入了一个之后自动对其进行跳转
                    if (!TextUtils.isEmpty(s.toString())) {
                        editTexts.get(position).setBackgroundResource(R.mipmap.input_licenseplate_click);
                        //变化不为空时才进行自动操作
                        if (s.toString().length() >= 2) {
                            editTexts.get(position).setText(s.toString().substring(1));
                            editTexts.get(position).setSelection(1);
                        }
                        //限制输入的是字母 则转换成大写
                        char code = editTexts.get(position).getText().toString().charAt(0);
                        if (code >= 97 && code <= 122) {
                            code -= 32;
                            editTexts.get(position).setText(code + "");
                            editTexts.get(position).setSelection(1);
                        }

                        //设置当前输入框中有内容
                        editTexts.get(position).setTag(true);
                        if (position < 6) {
                            //失去焦点
                            EditText currentEdt = editTexts.get(position);
                            //下一个 获取焦点
                            EditText nextEdt = editTexts.get(position + 1);
                            nextEdt.setFocusable(true);
                            nextEdt.setFocusableInTouchMode(true);
                            nextEdt.requestFocus();
                            nextEdt.findFocus();
                        }
                    } else {
                        editTexts.get(position).setBackgroundResource(R.mipmap.input_licenseplate_nor);
                    }
                    if (editTexts.get(7).getText().toString().equals("")) {
                        editTexts.get(7).setBackgroundResource(R.mipmap.input_newenergy);
                        editTexts.get(7).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                editTexts.get(7).setFocusable(true);
                                editTexts.get(7).setFocusableInTouchMode(true);
                                editTexts.get(7).requestFocus();
                                editTexts.get(7).findFocus();
                            }
                        });
                    } else {
                        editTexts.get(7).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                editTexts.get(7).setFocusable(true);
                                editTexts.get(7).setFocusableInTouchMode(true);
                                editTexts.get(7).requestFocus();
                                editTexts.get(7).findFocus();
                            }
                        });
                    }
                }
            });
            editTexts.get(i).setOnFocusChangeListener(new View.OnFocusChangeListener() {
                @Override
                public void onFocusChange(View v, boolean hasFocus) {
                    if (hasFocus) {
                        //获得焦点了，让其光标在最后
                        if (!TextUtils.isEmpty(editTexts.get(position).getText().toString())) {
                            editTexts.get(position).setSelection(1);
                        }
                    }
                }
            });
            editTexts.get(i).setOnKeyListener(new View.OnKeyListener() {
                @Override
                public boolean onKey(View v, int keyCode, KeyEvent event) {
                    if (keyCode == KeyEvent.KEYCODE_DEL) {
                        boolean isEmpty = (boolean) editTexts.get(position).getTag();
                        //删除事件
                        if (TextUtils.isEmpty(editTexts.get(position).getText().toString()) && position > 0) {
                            if (isEmpty) {
                                //第一次为空了  但是本次仍然停留在该输入框中
                                editTexts.get(position).setTag(false);
                            } else {
                                EditText previousEdt = editTexts.get(position - 1);
                                previousEdt.setText("");
                                previousEdt.setFocusable(true);
                                previousEdt.setFocusableInTouchMode(true);
                                previousEdt.requestFocus();
                                previousEdt.findFocus();
                                return true;
                            }
                        }
                    }
                    return false;
                }
            });
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()){
            case R.id.tv_addcar_btn:
                String carType = tv_car_type.getText().toString();
                if (TextUtils.isEmpty(carType)) {
                    CommonUtil.showToask(getApplicationContext(),"请选择类型");
                    return;
                }
                for (int i = 0; i < 7; i++) {
                    if (TextUtils.isEmpty(editTexts.get(i).getText().toString())) {
                        CommonUtil.showToask(getApplicationContext(),"车牌号填写不正确");
                        return;
                    }
                }
                if (urlArray.size() == 0) {
                    CommonUtil.showToask(getApplicationContext(),"车辆图片不能为空");
                    return;
                }
                if (urlArray.size() < 2 ) {
                    ToastUtils.showShort("车辆图片最少2张");
                    return;
                }
                String num = "";
                for (int i = 0; i < 7; i++) {
                    if (i == 1) {
                        num = num + editTexts.get(i).getText().toString();
                    }else {
                        num = num + editTexts.get(i).getText().toString();
                    }

                }
                if (!TextUtils.isEmpty(editTexts.get(7).getText().toString())) {
                    num = num + editTexts.get(7).getText().toString();
                }
                String photoList = "";
                for (int i = 0; i < urlArray.size(); i++) {
                    photoList = photoList + urlArray.get(i) +",";
                }
                if (TextUtils.isEmpty(photoList)) {
                    return;
                }
                photoList = photoList.substring(0,photoList.length()-1);

                addStall(carType,num,photoList);
                break;
            case R.id.tv_car_type:
                pvCustomOptions.show();
                break;
            default:
                break;
        }
    }

    //城市的数据
    private void initCustomOptionPicker() {
        pvCustomOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = carType.get(options1).toString();
                for (int i = 0; i < typeList.size(); i++) {
                    if (tx.equals(typeList.get(i).getValue())) {
                        keyType = typeList.get(i).getKey();
                        break;
                    }
                }
                tv_car_type.setText(tx);
            }
        }).setLayoutRes(R.layout.pickerview_time, new CustomListener() {
            @Override
            public void customLayout(View v) {
                final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                tvSubmit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        pvCustomOptions.returnData();
                        pvCustomOptions.dismiss();
                    }
                });
            }
        }).isDialog(false).build();
        pvCustomOptions.setPicker(carType);//添加数据
    }

    class GridImgAdapter extends BaseAdapter implements ListAdapter {
        @Override
        public int getCount() {
            return img_uri.size();
        }
        @Override
        public Object getItem(int position) {
            return null;
        }
        @Override
        public long getItemId(int position) {
            return position;
        }
        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            convertView = LayoutInflater.from(AddCarActivity.this).inflate(R.layout.activity_addstory_img_item, null);
            ViewHolder holder;
            if(convertView!=null){
                holder = new ViewHolder();
                convertView = LayoutInflater.from(AddCarActivity.this).inflate(R.layout.activity_addstory_img_item,null);
                convertView.setTag(holder);
            }else{
                holder = (ViewHolder) convertView.getTag();
            }
            holder.add_IB = (ImageView) convertView.findViewById(R.id.add_IB);
            holder.delete_IV = (ImageView) convertView.findViewById(R.id.delete_IV);
            AbsListView.LayoutParams param = new AbsListView.LayoutParams(screen_widthOffset, screen_widthOffset);
            convertView.setLayoutParams(param);
            if (img_uri.get(position) == null) {
                holder.delete_IV.setVisibility(View.GONE);
                holder.add_IB.setImageResource(R.mipmap.addimg);
                holder.add_IB.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View arg0) {
                        Intent intent = new Intent(AddCarActivity
                                .this, PhotoSelectorActivity.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                        intent.putExtra("limit", 3 - (img_uri.size() - 1));
                        startActivityForResult(intent, 0);
                    }
                });
            } else {
                Glide.with(AddCarActivity.this).load(img_uri.get(position).getUrl()).into(holder.add_IB);
                holder.add_IB.setImageResource(R.mipmap.addimg);
                holder.delete_IV.setOnClickListener(new View.OnClickListener() {
                    private boolean is_addNull;
                    @Override
                    public void onClick(View arg0) {
                        is_addNull = true;
                        img_uri.remove(position);
                        urlArray.remove(position);
                        single_photos.remove(position);
                        for (int i = 0; i < img_uri.size(); i++) {
                            if (img_uri.get(i) == null) {
                                is_addNull = false;
                                continue;
                            }
                        }
                        if (is_addNull) {
                            img_uri.add(null);
                        }
                        //FileUtils.DeleteFolder(img_url);//删除在emulate/0文件夹生成的图片
                        gridImgsAdapter.notifyDataSetChanged();
                    }
                });
                holder.add_IB.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("photos",(Serializable)single_photos);
                        bundle.putInt("position", position);
                        bundle.putBoolean("isSave",false);
                        bundle.putBoolean("isNet",true);
                        CommonUtils.launchActivity(AddCarActivity.this, PhotoPreviewActivity.class, bundle);
                    }
                });

            }
            return convertView;
        }
        class ViewHolder {
            ImageView add_IB;
            ImageView delete_IV;
        }
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case 0:
                if (data != null) {
                    List<String> paths = (List<String>) data.getExtras().getSerializable("photos");
                    if (img_uri.size() > 0) {
                        img_uri.remove(img_uri.size() - 1);
                    }
                    for (int i = 0; i < paths.size(); i++) {
                        if (FileUtil.fileExists(paths.get(i))) {
                            img_uri.add(new UploadGoodsBean(paths.get(i), false));
                            //上传参数
                            path = path + CommonUtil.bitmapToBase64(BitmapHelper.getImage(paths.get(i), 200))
                                    + "|";
                        }
                    }
                    if (path.length() > 0) {
                        path = path.substring(0, path.length() - 1);
                        sendImage(path, "2");//上传图片

                        if (img_uri.size() < 3) {
                            img_uri.add(null);
                        }
                        gridImgsAdapter.notifyDataSetChanged();
                    }
                }
                break;
            default:
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void sendImage(String img,String stallType){
        try {
            mRequest = NoHttp.createStringRequest(Urls.IP_UpImg, LrConstant.POST);
            mRequest.add("action", "FileUploadImage");
            mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));
            mRequest.add("phonePara", Application.DEVICE_ID);
            mRequest.add("type", stallType);
            mRequest.add("img", img);
            // 添加到请求队列+
            CallServer.getRequestInstance().add(baseContext, mRequest,
                    new CustomHttpListener<UpImgM>(baseContext, true, null) {
                        @Override
                        public void doWork(UpImgM data, String code) {
                        }

                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {
                            try {
                                super.onFinally(obj, code, isSucceed);
                                if (TextUtils.equals("1", code)) {
                                    String url = obj.getString("data");
                                    String[] arr = url.split(",");
                                    for (int i = 0; i < arr.length; i++) {
                                        urlArray.add(arr[i]);
                                    }
                                    for (int i = 0; i < urlArray.size(); i++) {
                                        PhotoModel photoModel = new PhotoModel();
                                        photoModel.setOriginalPath(urlArray.get(i));
                                        photoModel.setChecked(true);
                                        single_photos.add(photoModel);
                                    }
                                    path = "";
                                } else {
                                    CommonUtil.showToask(baseContext, obj.getString("msg"));
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }, true);
        } catch (Exception e) {
        }
    }

    private void addStall(String type,String num,String photo){
        try {
            mRequest = NoHttp.createStringRequest(Urls.CAR_IP, LrConstant.POST);
            if (carAgainRZ !=null) {
                mRequest.add("action", "EditCar");
                mRequest.add("Id",carAgainRZ.getId());
            } else {
                mRequest.add("action", "AddCar");
            }
            mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));
            mRequest.add("phonePara", Application.DEVICE_ID);
            mRequest.add("CarNum", num);
            mRequest.add("carType", keyType + "");
            mRequest.add("Photo",photo);
            // 添加到请求队列+
            CallServer.getRequestInstance().add(baseContext, mRequest,
                    new CustomHttpListener<UpImgM>(baseContext, true, null) {
                        @Override
                        public void doWork(UpImgM data, String code) {

                        }
                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {
                            if (TextUtils.equals("1", code)) {
                                finish();
                                if (carAgainRZ != null) {
                                    EventBus.getDefault().post(new CloseMyCarDetailEvent());
                                }
                            } else {
                                try {
                                    CommonUtil.showToask(baseContext, obj.getString("msg")+"");
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }, true);
        } catch (Exception e) {
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbinder.unbind();
    }


    private void stallType(){
        try {
            mRequest = NoHttp.createStringRequest(Urls.CAR_IP, LrConstant.POST);
            mRequest.add("action", "GetCarType");
            mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));
            mRequest.add("phonePara", Application.DEVICE_ID);

            // 添加到请求队列+
            CallServer.getRequestInstance().add(baseContext, mRequest,
                    new CustomHttpListener<UpImgM>(baseContext, true, null) {
                        @Override
                        public void doWork(UpImgM data, String code) {
                            if (TextUtils.equals("1", code)) {
                                CommonUtil.showToask(baseContext, data.getMsg()+"");
                            } else {
                                CommonUtil.showToask(baseContext, data.getMsg()+"");
                            }
                        }
                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {
                                try {
                                    super.onFinally(obj, code, isSucceed);
                                    if (TextUtils.equals("1", code)) {
                                        CommonUtil.showToask(baseContext, "111111");
                                    } else {
                                        CommonUtil.showToask(baseContext, "222222");
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }

                        }
                    }, true);
        } catch (Exception e) {
        }
    }
}
